import os,sys,glob
import time
import flask
import tornado.wsgi
import tornado.httpserver
from flask_cors import CORS # 跨域处理
import os
import cv2
import json
import logging
import base64
import matplotlib.pyplot as plt
from PIL import Image
from io import BytesIO
import mxnet as mx
import numpy as np
from matplotlib.patches import FancyArrowPatch,ArrowStyle
sys.path.append("./")
from common import set_logging,log_init,NpEncoder


os.environ["MXNET_CUDNN_AUTOTUNE_DEFAULT"]="3"
os.environ["CUDA_VISIBLE_DEVICES"]="0"


class Predictor(object):
    def __init__(self, ctx=None):
        self.ctx=ctx

    def __call__(self, image):
        h,w,c=image.shape
        assert h>50
        assert w>50
        normal_lines=[[10,20,30,40,1],[83.35931396484375, 66.51734161376953, 13.132840156555176, 114.67188262939453, 1.0]]
        arrow_lines=[[81.2734375, 153.29296875, 24.94533920288086, 193.125, 1.0]]
        solid_points=[[10,10],[15,5]]
        dashedline=[[83.28515625, 18.91015625, 81.2734375, 153.29296875, 1.0],]

        return normal_lines, arrow_lines,solid_points ,dashedline


if __name__ == '__main__':

    log_path="log/line_log.txt"
    # sys.path.append("../log")
    logger=set_logging(log_path,logging_name="LineDetect")

    DEBUG = False

    PORT = 28600  # sys.argv[1]
    app = flask.Flask(__name__)
    CORS(app, supports_credentials=True) #陌生的请求来访问你的服务器，自然需要进行授权。
    predictor = Predictor(ctx=None)


    @app.route('/detect_lines', methods=['POST'])  #url=ip+端口号+指令(detect_lines)
    def net_forward():
        remote_ip = flask.request.remote_addr
        logger.info(f"接口调用, 请求地址：{remote_ip}..........")

        try:
            para = json.loads(flask.request.get_data())
            user_image = para['Pic']
            user_image = base64.b64decode(user_image)
            img_array = np.fromstring(user_image, np.uint8)
            query_img = cv2.imdecode(img_array, cv2.COLOR_BGR2RGB)
            logger.info(f"The picture shape is {query_img.shape}")

            lines = predictor(query_img)

            return json.dumps({"results": lines}, cls=NpEncoder), 201
        except Exception as e:
            logging.exception(e)
            print("failed")

            logger.info(f"Line Detection Failed, error info: {e}\n\n")
            return flask.jsonify(str(e)), 400

    print("starting webserver...")
    if DEBUG:
        app.run(debug=True, host='0.0.0.0', port=PORT,threaded=True)
        # app.run(debug=True, host='0.0.0.0', port=PORT, threaded=True,processes=True)
    else:
        http_server = tornado.httpserver.HTTPServer(
            tornado.wsgi.WSGIContainer(app))
        http_server.listen(PORT, address="0.0.0.0")
        tornado.ioloop.IOLoop.instance().start()
